package com.example.myapplication.common.http;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.myapplication.util.SpUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 获取用户Token之后的http请求
 */
public class MyHttp {

    //用户登录专属请求码
    public static final int LOGIN_RESPONSE = 999;

    //用户登录token
    public static final int USER_TOKEN = 888;

    //连接超时5秒
    //响应数据超时5秒
    private OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(5,
            TimeUnit.SECONDS).build();

    private MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

    protected Handler mHandler = new MyHandler();

    public Handler getmHandler() {
        return mHandler;
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == -1) {
                Toast.makeText(mContext, "网络请求失败，请重新进入", Toast.LENGTH_SHORT).show();
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mContext instanceof Activity) {
                            ((Activity) mContext).finish();
                        }
                    }
                }, 1000);
                return;
            }
            //回调结果处理
            if (myHttpCallback != null) {
                myHttpCallback.doMessage(msg);
            }
        }
    }

    //回调结果处理
    private MyHttpCallback myHttpCallback;

    private Context mContext;

    public MyHttp(Context context, MyHttpCallback myHttpCallback) {
        this.mContext = context;
        this.myHttpCallback = myHttpCallback;
    }

    /**
     * post方式发送请求
     *
     * @param url
     * @param jsonParams
     * @param requestCode
     */
    public void queryHttpPost(String url, String jsonParams, int requestCode) {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        //添加固定头部
        builder.addHeader("X-Auth-Token", new SpUtil(mContext).getValue("userconfig", "token"));
        builder.addHeader("Content-Type", "application/json;charset=UTF-8");
        //post方式添加请求参数
        builder.post(RequestBody.create(jsonType, jsonParams));
        Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Message message = Message.obtain();
                message.obj = string;
                message.what = requestCode;
                mHandler.sendMessage(message);
            }
        });
    }


    /**
     * get方式发送请求
     *
     * @param url
     * @param requestCode
     */
    public void queryHttpGet(String url, int requestCode) {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        //添加固定头部
        builder.addHeader("X-Auth-Token", new SpUtil(mContext).getValue("userconfig", "token"));
        builder.addHeader("Content-Type", "application/json;charset=UTF-8");
        Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Message message = Message.obtain();
                message.obj = string;
                message.what = requestCode;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 华为云lot用户登录专属
     *
     * @param loginurl
     * @param account
     * @param username
     * @param password
     */
    public void queryHttpByLogin(String loginurl, String account, String username, String password, String project_id) {
        //组装用户登录token请求参数
        String token_request_param = "{\n" +
                " \"auth\": {\n" +
                "  \"identity\": {\n" +
                "   \"methods\": [\n" +
                "    \"password\"\n" +
                "   ],\n" +
                "   \"password\": {\n" +
                "    \"user\": {\n" +
                "     \"domain\": {\n" +
                "      \"name\": \"" + account + "\"\n" +
                "     },\n" +
                "     \"name\": \"" + username + "\",\n" +
                "     \"password\": \"" + password + "\"\n" +
                "    }\n" +
                "   }\n" +
                "  },\n" +
                "  \"scope\": {\n" +
                "   \"project\": {\n" +
                "    \"id\": \"" + project_id + "\"\n" +
                "   }\n" +
                "  }\n" +
                " }\n" +
                "}";

        Request request =
                new Request.Builder().url(loginurl).post(RequestBody.create(jsonType, token_request_param)).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("zoubo", "success");
                String token = response.header("X-Subject-Token");
                Log.d("zoubo", token);
                //存取token
                Message message = Message.obtain();
                message.obj = token;
                message.what = LOGIN_RESPONSE;
                mHandler.sendMessage(message);
            }
        });
    }


    /**
     * 检查用户token有效性
     *
     * @param url
     * @param token
     */
    public void queryHttpByToken(String url, String token) {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        //添加固定头部
        builder.addHeader("X-Auth-Token", new SpUtil(mContext).getValue("userconfig", "token"));
        builder.addHeader("Content-Type", "application/json;charset=UTF-8");
        builder.addHeader("X-Subject-Token", token);
        Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = Message.obtain();
                //响应状态
                message.obj = response.code();
                message.what = USER_TOKEN;
                mHandler.sendMessage(message);
            }
        });
    }
}

